package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.HiasTeamClerkBo;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.HiasClerkMapper;
import com.ruoyi.system.mapper.HiasTeamClerkMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.HiasTeamBo;
import com.ruoyi.system.mapper.HiasTeamMapper;
import com.ruoyi.system.service.IHiasTeamService;

import java.util.*;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-11
 */
@RequiredArgsConstructor
@Service
public class HiasTeamServiceImpl implements IHiasTeamService {

    private final HiasTeamMapper baseMapper;
    private final HiasClerkMapper clerkMapper;
    private final HiasTeamClerkMapper teamClerkMapper;

    /**
     * 查询【请填写功能名称】
     */
    @Override
    public HiasTeamVo queryById(Long teamId){
        HiasTeamVo teamVo = new HiasTeamVo();
        HiasTeam team = baseMapper.selectById(teamId);
        teamVo.setId(team.getId());
        teamVo.setTeamIntro(team.getTeamIntro());
        teamVo.setTeamName(team.getTeamName());
        teamVo.setMail(team.getMail());
        teamVo.setAddress(team.getAddress());
        teamVo.setOrganizationId(team.getOrganizationId());
        QueryWrapper<HiasTeamClerk> teamClerkQueryWrapper = new QueryWrapper<>();
        teamClerkQueryWrapper.eq(teamId!=null, "team_id", teamId);
        teamClerkQueryWrapper.eq("apply_status", TeamApplyStatus.PASS.getCode());
        List<HiasTeamClerk> teamClerks = teamClerkMapper.selectList(teamClerkQueryWrapper);
        List<HiasTeamApplyClerkVo> applyClerkVos = new ArrayList<>();
        for (int i = 0; i < teamClerks.size(); i++) {
            HiasTeamApplyClerkVo clerkVo = new HiasTeamApplyClerkVo();
            clerkVo.setTeamClerkApplyId(teamClerks.get(i).getId());
            clerkVo.setClerkId(teamClerks.get(i).getClerkId());
            clerkVo.setApplyTime(teamClerks.get(i).getApplyTime());
            clerkVo.setWorkMode(TeamWorkMode.getWorkMode(teamClerks.get(i).getWorkMode()));
            clerkVo.setApplyStatus(TeamApplyStatus.getStatus(teamClerks.get(i).getApplyStatus()));
            HiasClerk clerk = clerkMapper.selectById(teamClerks.get(i).getClerkId());
            if(clerk != null) {
                clerkVo.setEmail(clerk.getMail());
                clerkVo.setIntro(clerk.getIntro());
                clerkVo.setClerkName(clerk.getClerkName());
            }
            applyClerkVos.add(clerkVo);
        }
        teamVo.setClerkList(applyClerkVos);
        return teamVo;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<HiasTeamVo> queryPageList(HiasTeamBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HiasTeam> lqw = buildQueryWrapper(bo);
        Page<HiasTeamVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<HiasTeamVo> queryList(HiasTeamBo bo) {
        LambdaQueryWrapper<HiasTeam> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HiasTeam> buildQueryWrapper(HiasTeamBo bo) {
        //Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HiasTeam> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTeamName()), HiasTeam::getTeamName, bo.getTeamName());
        lqw.eq(StringUtils.isNotBlank(bo.getTeamIntro()), HiasTeam::getTeamIntro, bo.getTeamIntro());
        lqw.eq(bo.getOrganizationId() != null, HiasTeam::getOrganizationId, bo.getOrganizationId());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), HiasTeam::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getMail()), HiasTeam::getMail, bo.getMail());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(HiasTeamBo bo) {
        HiasTeam add = BeanUtil.toBean(bo, HiasTeam.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTeamName(add.getTeamName());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(HiasTeamBo bo) {
        HiasTeam update = BeanUtil.toBean(bo, HiasTeam.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HiasTeam entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean join(HiasTeamClerkBo hiasTeamClerkBo) {
        QueryWrapper<HiasTeam> wrapper = new QueryWrapper<>();
        wrapper.eq("id", hiasTeamClerkBo.getTeamId());
        boolean teamExist = baseMapper.exists(wrapper);

        QueryWrapper<HiasClerk> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id", hiasTeamClerkBo.getClerkId());
        boolean clerkExist = clerkMapper.exists(wrapper1);

        QueryWrapper<HiasTeamClerk> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("clerk_id",hiasTeamClerkBo.getClerkId());
        wrapper2.eq("team_id",hiasTeamClerkBo.getTeamId());
        wrapper2.eq("apply_status", TeamApplyStatus.PASS.getCode());
        boolean isJoin = teamClerkMapper.exists(wrapper2);

        if(teamExist && clerkExist && !isJoin){
            HiasTeamClerk item = new HiasTeamClerk();
            item.setTeamId(hiasTeamClerkBo.getTeamId());
            item.setClerkId(hiasTeamClerkBo.getClerkId());
            item.setWorkMode(hiasTeamClerkBo.getWorkMode());
            item.setApplyStatus(TeamApplyStatus.NEW.getCode());
            item.setApplyTime(new Date());
            teamClerkMapper.insert(item);
            return true;
        }else {
            return false;
        }


    }

    /**
     * @info 查询团队加入申请记录
     * @param teamId 团队ID
     * @return HiasTeamApplyVo
     */
    @Override
    public HiasTeamApplyVo applyList(Long teamId) {
        HiasTeamApplyVo applyVo = new HiasTeamApplyVo();
        //查询团队信息
        HiasTeam team = baseMapper.selectById(teamId);
        QueryWrapper<HiasTeamClerk> teamClerkQueryWrapper = new QueryWrapper<>();
        teamClerkQueryWrapper.eq(teamId!=null, "team_id", teamId);
        teamClerkQueryWrapper.eq(teamId!=null, "apply_status", TeamApplyStatus.PASS.getCode());
        Long teamSize = teamClerkMapper.selectCount(teamClerkQueryWrapper);
        applyVo.setTeamSize(teamSize);
        applyVo.setTeamName(team.getTeamName());
        applyVo.setTeamId(team.getId());
        //清理一下原有的查询条件
        teamClerkQueryWrapper.clear();
        //查询团队加入申请记录
        teamClerkQueryWrapper.eq(teamId!=null, "team_id", teamId);
        teamClerkQueryWrapper.eq(teamId!=null, "apply_status", TeamApplyStatus.NEW.getCode());
        teamClerkQueryWrapper.orderByAsc("apply_time");
        List<HiasTeamClerk> teamNewClerks = teamClerkMapper.selectList(teamClerkQueryWrapper);
        List<HiasTeamApplyClerkVo> teamApplyClerkVos = new ArrayList<>();
        for (int i = 0; i < teamNewClerks.size(); i++) {
            //根据申请记录查询对应的职员
            Long clerkId = teamNewClerks.get(i).getClerkId();
            HiasClerk clerk = clerkMapper.selectById(clerkId);
            if (clerk != null) {
                //如果职员确实存在，则将其信息放到返回结果中
                HiasTeamApplyClerkVo applyClerkVo = new HiasTeamApplyClerkVo();
                //填充VO中关于成员的信息
                applyClerkVo.setTeamClerkApplyId(teamNewClerks.get(i).getId());
                applyClerkVo.setClerkId(clerkId);
                applyClerkVo.setClerkName(clerk.getClerkName());
                applyClerkVo.setIntro(clerk.getIntro());
                applyClerkVo.setEmail(clerk.getMail());
                applyClerkVo.setApplyTime(teamNewClerks.get(i).getApplyTime());
                //返回给页面的数据应该是字符串描述实际的关系，而不是数据库中存储的数字，需要在枚举中转化成字符串
                applyClerkVo.setApplyStatus(TeamApplyStatus.getStatus(teamNewClerks.get(i).getApplyStatus()));
                applyClerkVo.setWorkMode(TeamWorkMode.getWorkMode(teamNewClerks.get(i).getWorkMode()));
                teamApplyClerkVos.add(applyClerkVo);
            }
        }
        applyVo.setApplyClerkVos(teamApplyClerkVos);
        return applyVo;
    }

    @Override
    public HiasTeamRecordVo applyRecords(Long clerkId) {
        HiasTeamRecordVo result = new HiasTeamRecordVo();
        HiasClerk clerk = clerkMapper.selectById(clerkId);
        //填充VO中成员信息的部分
        if(clerk != null) {
            result.setClerkId(clerk.getId());
            result.setClerkName(clerk.getClerkName());
        }

        //查询对应成员的申请记录
        QueryWrapper<HiasTeamClerk> teamClerkQueryWrapper = new QueryWrapper<>();
        teamClerkQueryWrapper.eq(clerkId != null, "clerk_id", clerkId);
        List<HiasTeamClerk> teamClerks = teamClerkMapper.selectList(teamClerkQueryWrapper);
        List<HiasTeamApplyRecordVo> teamApplyRecordVos = new ArrayList<>();
        for (int i = 0; i < teamClerks.size(); i++) {
            //填充VO中关于申请的内容
            HiasTeamApplyRecordVo applyRecordVo = new HiasTeamApplyRecordVo();
            applyRecordVo.setTeamClerkApplyId(teamClerks.get(i).getId());
            applyRecordVo.setApplyMark(teamClerks.get(i).getApplyMark());
            applyRecordVo.setApplyTime(teamClerks.get(i).getApplyTime());
            applyRecordVo.setApplyStatus(TeamApplyStatus.getStatus(teamClerks.get(i).getApplyStatus()));
            HiasTeam team = baseMapper.selectById(teamClerks.get(i).getTeamId());
            //填充VO中关于所申请的团队的信息
            if(team != null) {
                applyRecordVo.setTeamId(team.getId());
                applyRecordVo.setTeamName(team.getTeamName());
            }
            teamApplyRecordVos.add(applyRecordVo);
        }
        result.setApplyRecordVos(teamApplyRecordVos);
        return result;
    }

    @Override
    public boolean checkApply(HiasTeamClerkBo teamClerkBo) {
        HiasTeamClerk teamClerk = new HiasTeamClerk();
        //判断ID是否为空
        if(teamClerkBo.getId() != null) {
            teamClerk.setId(teamClerkBo.getId());
        }

        //判断审批状态
        if(teamClerkBo.getApplyStatus() != null) {
            teamClerk.setApplyStatus(teamClerkBo.getApplyStatus());
            if(teamClerkBo.getApplyStatus()==TeamApplyStatus.FAIL.getCode()) {
                teamClerk.setApplyMark(teamClerkBo.getApplyMark());
            }
            else if(teamClerkBo.getApplyStatus()==TeamApplyStatus.PASS.getCode()) {
                teamClerk.setApplyMark("审批通过");
            }
        }
        //更新数据库中的审批状态
        teamClerkMapper.updateById(teamClerk);
        return true;
    }
}
